import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression, Lasso, Ridge, Lars
from sklearn.metrics import mean_squared_error, r2_score

file_name = r".\数据\1013\多元线性回归的例子.xlsx"

data = pd.read_excel(file_name)

x = data[['地铁', '电视', '媒体']].values
y = data['销售额'].values


#模型1
model = LinearRegression()
model.fit(x, y)

#测试
test_data = np.array([100, 100, 100]).reshape((1, -1))
y_test_predict = model.predict(test_data)
print("线性回归模型预测销售额：", y_test_predict[0])

#评估模型
y_predict = model.predict(x)
mse = mean_squared_error(y, y_predict)
m1r2 = r2_score(y, y_predict)
print("线性回归模型均方误差：", mse)
print("线性回归模型R-squared：", m1r2)

#模型2
lasso = Lasso()
lasso.fit(x, y)

#测试
y_test_predict = lasso.predict(test_data)
print("Lasso模型预测销售额：", y_test_predict[0])

#评估模型
y_predict = lasso.predict(x)
mse = mean_squared_error(y, y_predict)
m2r2 = r2_score(y, y_predict)
print("Lasso模型均方误差：", mse)
print("Lasso模型R-squared：", m2r2)

#模型3
ridge = Ridge()
ridge.fit(x, y)

#测试
y_test_predict = ridge.predict(test_data)
print("Ridge模型预测销售额：", y_test_predict[0])

#评估模型
y_predict = ridge.predict(x)
mse = mean_squared_error(y, y_predict)
m3r2 = r2_score(y, y_predict)
print("Ridge模型均方误差：", mse)
print("Ridge模型R-squared：", m3r2)

#模型4
lars = Lars()
lars.fit(x, y)

#测试
y_test_predict = lars.predict(test_data)
print("Lars模型预测销售额：", y_test_predict[0])

#评估模型
y_predict = lars.predict(x)
mse = mean_squared_error(y, y_predict)
m4r2 = r2_score(y, y_predict)
print("Lars模型均方误差：", mse)
print("Lars模型R-squared：", m4r2)

#通过r2_score来比较模型的优劣
if m1r2 == max(m1r2, m2r2, m3r2, m4r2):
    print("线性回归模型效果最好")
elif m2r2 == max(m1r2, m2r2, m3r2, m4r2):
    print("Lasso模型效果最好")
elif m3r2 == max(m1r2, m2r2, m3r2, m4r2):
    print("Ridge模型效果最好")
else:
    print("Lars模型效果最好")